<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/29
 * Time: 14:13
 */

namespace Admin\Controller;

use Common\Common\FileSystem;
use Common\Common\ResponseResult;
use Common\Common\Validator;
use Common\Model\Auth;
use Common\Model\Role;
use Common\Model\RoleUsers;

class UserController extends \Think\Controller
{

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 登录页面
     */
    public function login()
    {
        if (Auth::check()) {
            header('location:/admin/index');
            die();
        }
        if (IS_POST) {
            $validator = Validator::make($_POST, [
                'email' => ['required', 'email', 'exists:users,email'],
                'password' => ['required', 'min:6', 'max:32'],
                'code' => ['required', 'max:4', 'min:4', 'code']
            ]);
            if ($validator->filed()) {
                ResponseResult::error(2000, $validator->error());
            }
            $status = Auth::login($_POST['email'], $_POST['password']);
            if ($status === true) {
                ResponseResult::success('Login Is Successfully');
            } else {
                ResponseResult::error(1000, $status);
            }
        } else {
            $this->display();
        }
    }

    /**
     * 注册页面
     */
    public function register()
    {
        if (Auth::check()) {
            header('location:/admin/index');
            die();
        }
        $this->display();
    }

    /**
     * 重置密码页面
     */
    public function forgotPassword()
    {
        if (Auth::check()) {
            header('location:/admin/index');
            die();
        }
        $this->display('forgot-password');
    }


    /**
     * 添加用户
     */
    public function insertUser()
    {
        if (IS_POST) {
            $this->validatorUser();
            $user = M('users');
            $data = $user->create();

            $defaultRole = Role::defaultRole();
            if ($defaultRole === null) {
                ResponseResult::error(2000, ['username' => '无法注册，缺少默认的用户组，联系管理员设置']);
            }

            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            $data['avatar'] = FileSystem::uploadFile('avatar');
            $users_id = $user->add($data);
            if ($users_id) {
                RoleUsers::createUserRole($users_id, $defaultRole->id);
                ResponseResult::success('创建成功');
            } else {
                ResponseResult::error(1000, $user->getError());
            }
        } else {
            $this->error('请求错误', '/admin/register');
        }
    }

    private function validatorUser()
    {
        $array = array();
        $model = M('users');
        $username = isset($_POST['username']) ? $_POST['username'] : null;

        if (preg_match('/^\w{4,32}/', $username) === 0) {
            $array['username'] = '用户名必须在4-32位之间';
        }
        if (!empty($model->where("username = '{$username}'")->find())) {
            $array['username'] = '用户名已存在';
        }

        $email = isset($_POST['email']) ? $_POST['email'] : null;
        $reg = '/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/';
        if (preg_match($reg, $email) === 0) {
            $array['email'] = '邮箱格式不正确';
        }
        if (!empty($model->where("email = '{$email}'")->find())) {
            $array['email'] = '邮箱已存在';
        }
        $password = isset($_POST['password']) ? $_POST['password'] : null;

        if (preg_match('/\w{6,32}/', $password) === 0) {
            $array['password'] = '密码必须在6-32位之间';
        }

        $password_c = isset($_POST['password_c']) ? $_POST['password_c'] : null;

        if ($password !== $password_c) {
            $array['password_c'] = '两次输入的密码不一致';
        }

        $age = isset($_POST['age']) ? intval($_POST['age']) : 0;
        if ($age <= 0 || $age > 200) {
            $array['age'] = '年龄必须大于0 小于200';
        }

        $avatar = isset($_FILES['avatar']) ? $_FILES['avatar'] : null;
        if ($avatar === null) {
            $array['avatar'] = '头像必须上传';
        }

        $sex = isset($_POST['sex']) ? intval($_POST['sex']) : null;
        if ($sex === null) {
            $array['sex'] = '性别必须选择';
        }

        if (!empty($array)) {
            ResponseResult::error(2000, $array);
        }
    }
}
